<template>
  <div class="map-container">
    <div id="mapContainer" class="map-wrapper"></div>
    <div class="location-info" v-if="currentLocation">
      <p>经度: {{ currentLocation.lng }}</p>
      <p>纬度: {{ currentLocation.lat }}</p>
      <p>定位时间: {{ locationTime }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

// 定义响应式数据
const map = ref(null)
const marker = ref(null)
const currentLocation = ref(null)
const locationTime = ref('')
let amapInstance = null
let watchPositionId = null

// 初始化地图
const initMap = async () => {
  try {
    amapInstance = await AMapLoader.load({
      key: '5c4955ec3d2015ee4171cec5903f7fdd', // 替换为你的高德地图Key
      version: '2.0',
      plugins: ['AMap.Geolocation']
    })

    // 创建地图实例
    map.value = new amapInstance.Map('mapContainer', {
      zoom: 15,
      center: [116.397428, 39.90923] // 默认中心点（北京）
    })

    // 创建定位插件
    const geolocation = new amapInstance.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0,
      convert: true,
      showButton: true,
      buttonPosition: 'LB',
      buttonOffset: new amapInstance.Pixel(10, 20),
      showMarker: true,
      showCircle: true,
      panToLocation: true,
      zoomToAccuracy: true
    })

    map.value.addControl(geolocation)

    // 启动实时定位
    startRealTimeLocation(geolocation)
  } catch (error) {
    console.error('地图加载失败:', error)
  }
}

// 启动实时定位
const startRealTimeLocation = (geolocation) => {
  // 先获取一次当前位置
  geolocation.getCurrentPosition((status, result) => {
    if (status === 'complete') {
      updatePosition(result)
    } else {
      console.error('定位失败:', result.message)
    }
  })

  // 开启持续定位监听
  watchPositionId = geolocation.watchPosition((status, result) => {
    if (status === 'complete') {
      updatePosition(result)
    } else {
      console.error('定位失败:', result.message)
    }
  })
}

// 更新位置信息
const updatePosition = (position) => {
  const { position: pos, accuracy } = position
  currentLocation.value = {
    lng: pos.lng,
    lat: pos.lat
  }
  
  locationTime.value = new Date().toLocaleString()
  
  // 更新地图中心点
  if (map.value) {
    map.value.setCenter([pos.lng, pos.lat])
    
    // 如果标记不存在则创建标记
    if (!marker.value) {
      marker.value = new amapInstance.Marker({
        position: [pos.lng, pos.lat],
        title: '当前位置',
        map: map.value
      })
    } else {
      // 更新标记位置
      marker.value.setPosition([pos.lng, pos.lat])
    }
    
    // 添加精度圆圈
    if (accuracy > 0) {
      const circle = new amapInstance.Circle({
        center: [pos.lng, pos.lat],
        radius: accuracy,
        strokeColor: '#0066FF',
        strokeOpacity: 0.5,
        strokeWeight: 1,
        fillColor: '#0066FF',
        fillOpacity: 0.3,
        map: map.value
      })
      
      // 清除之前的圆圈
      setTimeout(() => {
        circle.setMap(null)
      }, 3000)
    }
  }
}

// 停止定位监听
const stopLocationWatch = () => {
  if (watchPositionId && amapInstance) {
    const geolocation = new amapInstance.Geolocation()
    geolocation.clearWatch(watchPositionId)
  }
}

// 组件挂载时初始化地图
onMounted(() => {
  initMap()
})

// 组件卸载前清理资源
onBeforeUnmount(() => {
  stopLocationWatch()
  if (map.value) {
    map.value.destroy()
  }
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-wrapper {
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.location-info {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  z-index: 10;
}

.location-info p {
  margin: 5px 0;
  font-size: 14px;
}
</style>